import { createPinia } from 'pinia';
import useAppStore from './modules/app';
import useUserStore from './modules/user';
import useTabBarStore from './modules/tab-bar';

const persistUserPlugin = (context: any) => {
  const { store } = context;
  if (store.$id !== 'user') return;

  const key = 'pinia-user';
  const fromLS = localStorage.getItem(key);
  if (fromLS) {
    try {
      store.$patch(JSON.parse(fromLS));
    } catch (e) {
      // 读取失败时忽略
    }
  }

  store.$subscribe(
    (_: any, state: any) => {
      localStorage.setItem(key, JSON.stringify(state));
    },
    { detached: true }
  );
};

const pinia = createPinia();
pinia.use(persistUserPlugin);

export { useAppStore, useUserStore, useTabBarStore };
export default pinia;
